import React, { useState, useEffect} from 'react'
import { Form } from 'antd'
const FormItem = Form.Item
import { uniqueFun } from '@/common/utils'

import { FormWidgetProps } from './WidgetRender'
import { ListenerItem, ConditionItem, OptionsFetch, UpdateByWatch } from '../index'
interface WatchNames{
  name: string
  type: 'options' | 'listeners'
}

function index({ newSchema, setNewSchema, formInstance, children }: FormWidgetProps) {
  const [updateByWatch, setUpdateByWatch] = useState<UpdateByWatch>({name: '', value: null, type: 'listeners'})
  const watchNames:WatchNames[] = [] // 侦听的字段集
  if (newSchema?.listeners?.length && newSchema?.listeners.some((li: ListenerItem) => li?.watch?.length)) {
    newSchema?.listeners.forEach((lis: ListenerItem) => {
      lis.watch.forEach((w: string) => {
        watchNames.push({ name: w, type: 'listeners' })
      })
    })
  }
  if (Object.prototype.toString.call(newSchema?.options) === '[object Object]' && (newSchema?.options as OptionsFetch)?.watch?.length) {
    (newSchema?.options as any).watch.forEach((w: string) => {
      watchNames.push({ name: w, type: 'options' })
    })
  }

  useEffect(() => {
    if (updateByWatch.name || updateByWatch.value || updateByWatch.type) {
      const tmpNewSchema = { ...JSON.parse(JSON.stringify(newSchema))}
      if (updateByWatch.type.includes('options')) {
        // 侦听的字段是options类型下拉更改导致的场景
      }
      if (updateByWatch.type.includes('listeners')) {
        // 侦听的字段是listeners类型监听导致的场景
        tmpNewSchema.listeners.forEach((item: ListenerItem) => {
          let expression: string = ''
          item.condition.forEach((cd: ConditionItem) => {
            const fieldValTmp = formInstance.getFieldValue(cd.fieldName)
            const fieldVal = Object.prototype.toString.call(fieldValTmp) === '[object Object]' ? fieldValTmp?.value : fieldValTmp
            expression += ` ${cd.connector} ${fieldVal} ${cd.operator} ${cd.value}`
          })
          if (eval(`(${expression.substring(3)})`)) {
            Object.keys(item.set).forEach((k: string) => {
              // 有多个条件符合场景下只执行备份一次
              // eslint-disable-next-line no-prototype-builtins
              if (tmpNewSchema.hasOwnProperty(k) && Object.keys(tmpNewSchema).filter((ik: string) => ik.includes(k)).length === 1) {
                tmpNewSchema[`origin_${k}`] = tmpNewSchema[k] // 上一次的值得备份
                let setVal:any = item.set[k]
                if (item.set[k]?.includes('.')) {
                  // 存在.链接符场景代表需要处理取值 例：slotType.value.price
                  console.log('updateByWatch', updateByWatch)
                  const setWatchFieldName:string = setVal.split('.')[0]
                  const setFieldName:string = setVal.split('.')[2]
                  const setFieldValueKey:string = setVal.split('.')[1]
                  if (setFieldValueKey === 'value') {
                    if (updateByWatch.name === setWatchFieldName) {
                      setVal = updateByWatch.value[setFieldName]
                    }
                  }
                }
                tmpNewSchema[k] = setVal
                console.log('tmpNewSchema', tmpNewSchema)
              }
            })
          } else {
            // 不符合得注意重置为原始值
            Object.keys(tmpNewSchema).forEach((k: string) => {
              if (k.includes('origin_')) {
                const originK = k.substring(4)
                tmpNewSchema[originK] = tmpNewSchema[k]
                delete tmpNewSchema[k]
              }
            })
          }
          // console.log('expression',expression.substring(3))
        })
      }
      tmpNewSchema.updateByWatch = updateByWatch
      // console.log('updateByWatch', updateByWatch, newSchema,tmpNewSchema)
      setNewSchema(tmpNewSchema)
    }
  }, [updateByWatch.name, updateByWatch.value, updateByWatch.type])

  return (
    <FormItem
      noStyle
      shouldUpdate={(prevValues, curValues) => {
        let flag = false
        // console.log('shouldUpdate', prevValues, curValues)
        // 1.非动态增减表单场景
        // 2.动态增减表单场景
        if (Object.keys(curValues)) {
          const watchNameArr = [...JSON.parse(JSON.stringify(uniqueFun(watchNames, 'name')))]
          watchNameArr.forEach((wn: WatchNames) => {
            if (Object.prototype.toString.call(curValues[wn.name]) === '[object Object]') {
              if (curValues[wn.name]?.value !== prevValues[wn.name]?.value) {
                setUpdateByWatch({ name: wn.name, value: curValues[wn.name], type: wn.type })
                flag = true
              }
            } else {
              if (curValues[wn.name] !== prevValues[wn.name]) {
                setUpdateByWatch({ name: wn.name, value: curValues[wn.name], type: wn.type })
                flag = true
              }
            }
          })
        }
        return flag
      }}
    >
      {() => {
        // console.log('getFieldValue',schema,updateByWatch)
        return <>
          {
            newSchema.status === 'hidden' ? null : children
            // schema.status === 'hidden' ? null : React.Children.map(children, (element) => {
            //   return (
            //     React.isValidElement(element) &&
            //     React.cloneElement(element, {
            //       schema: {
            //         ...schema, updateByWatchFiled: updateByWatch.filed,
            //         options: {
            //           ...(schema?.options as optionsFetch),
            //           params: { ...(schema?.options as optionsFetch)?.params, [updateByWatch.filed]: updateByWatch.value}
            //         }
            //       },
            //       key: `${schema.fieldName}`
            //     } as any)
            //   )
            // })
          }
        </>
      }}
    </FormItem>
  )
}
export default index
